
include(ExternalProject)

# TensorRT头文件路径
set(TENSORRT_INCLUDE_DIR_USER "/usr/include" CACHE PATH "Path to TensorRT include directory")

if (ENABLE_NNDEPLOY_INFERENCE_TENSORRT STREQUAL "OFF")
elseif (ENABLE_NNDEPLOY_INFERENCE_TENSORRT STREQUAL "ON")
  find_path(
    TENSORRT_INCLUDE_DIR NvInfer.h
    HINTS ${TENSORRT_INCLUDE_DIR_USER} ${CUDA_TOOLKIT_ROOT_DIR})
  message(STATUS "Found TensorRT headers at ${TENSORRT_INCLUDE_DIR}")
  include_directories(${TENSORRT_INCLUDE_DIR})
  set(NNDEPLOY_THIRD_PARTY_LIBRARY ${NNDEPLOY_THIRD_PARTY_LIBRARY} libnvinfer.so)
  set(NNDEPLOY_THIRD_PARTY_LIBRARY ${NNDEPLOY_THIRD_PARTY_LIBRARY} libnvinfer_plugin.so)
  set(NNDEPLOY_THIRD_PARTY_LIBRARY ${NNDEPLOY_THIRD_PARTY_LIBRARY} libnvparsers.so)
  set(NNDEPLOY_THIRD_PARTY_LIBRARY ${NNDEPLOY_THIRD_PARTY_LIBRARY} libnvonnxparser.so)
else()
  if(IS_ABSOLUTE ${ENABLE_NNDEPLOY_INFERENCE_TENSORRT})
    # Absolute path, use directly
    set(ENABLE_NNDEPLOY_INFERENCE_TENSORRT ${ENABLE_NNDEPLOY_INFERENCE_TENSORRT})
    message(STATUS "Using absolute path for TENSORRT: ${ENABLE_NNDEPLOY_INFERENCE_TENSORRT}")
  else()
    # Relative path, relative to project root directory
    set(ENABLE_NNDEPLOY_INFERENCE_TENSORRT ${CMAKE_SOURCE_DIR}/${ENABLE_NNDEPLOY_INFERENCE_TENSORRT})
    message(STATUS "Using relative path for TENSORRT: ${ENABLE_NNDEPLOY_INFERENCE_TENSORRT}")
    # Update ENABLE_NNDEPLOY_INFERENCE_TENSORRT to absolute path
    set(ENABLE_NNDEPLOY_INFERENCE_TENSORRT ${ENABLE_NNDEPLOY_INFERENCE_TENSORRT})
  endif()
  include_directories(${ENABLE_NNDEPLOY_INFERENCE_TENSORRT}/include)
  set(LIB_PATH ${ENABLE_NNDEPLOY_INFERENCE_TENSORRT}/${NNDEPLOY_THIRD_PARTY_LIBRARY_PATH_SUFFIX})
  set(LIBS "nvinfer" "nvinfer_plugin" "nvparsers" "nvonnxparser")
  foreach(LIB ${LIBS})
    set(LIB_NAME ${NNDEPLOY_LIB_PREFIX}${LIB}${NNDEPLOY_LIB_SUFFIX})
    set(FULL_LIB_NAME ${LIB_PATH}/${LIB_NAME})
    if(IS_SYMLINK ${FULL_LIB_NAME})
      get_filename_component(REAL_LIB_NAME ${FULL_LIB_NAME} REALPATH)
      # message(STATUS "Real path of ${FULL_LIB_NAME}: ${REAL_LIB_NAME}")
      set(FULL_LIB_NAME ${REAL_LIB_NAME})
      # message(STATUS "Full lib name: ${FULL_LIB_NAME}")
    endif()
    set(NNDEPLOY_THIRD_PARTY_LIBRARY ${NNDEPLOY_THIRD_PARTY_LIBRARY} ${FULL_LIB_NAME})    
  endforeach()

  if(SYSTEM_Windows)
    set(BIN_PATH ${ENABLE_NNDEPLOY_INFERENCE_TENSORRT}/bin)
    link_directories(${BIN_PATH})
    file(GLOB_RECURSE SET_BIN_PATH ${BIN_PATH}/*.dll*)
    foreach(SET_BIN_PATH ${SET_BIN_PATH})
      file(COPY ${SET_BIN_PATH} DESTINATION ${EXECUTABLE_OUTPUT_PATH}/${CMAKE_BUILD_TYPE})
    endforeach()
  endif()
  install(DIRECTORY ${ENABLE_NNDEPLOY_INFERENCE_TENSORRT} DESTINATION ${NNDEPLOY_INSTALL_THIRD_PARTY_PATH})
endif()